package com.chinadrtv.batch.admin.controller.ozing;

import com.chinadrtv.user.model.User;
import com.chinadrtv.user.model.ozing.auth.OzingResource;
import com.chinadrtv.user.model.ozing.auth.OzingRole;
import com.chinadrtv.user.model.ozing.auth.OzingUser;
import com.chinadrtv.user.service.ozing.IAuthService;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: zhouxieguo
 * Date: 13-5-14
 * Time: 上午11:02
 */
@Controller
public class AuthController {

    public final static String OZING_CATEGORY = "batch";
    public final static String[] OZING_ADMIN_DEFAULT_ROLES = new String[]{"ROLE_ADMIN"};

    @Autowired
    private IAuthService authManager;

    private static ObjectMapper mapper = new ObjectMapper();

    @RequestMapping(value = "/auth", method = RequestMethod.GET)
    public String toAuthPage(HttpServletRequest request, HttpServletResponse response, Model model) {
        List<OzingUser> ozingUsers = authManager.getAllUsers(OZING_CATEGORY);
        List<OzingRole> ozingRoles = authManager.getAllRoles(OZING_CATEGORY);
        List<OzingResource> ozingResources = authManager.getAllResources(OZING_CATEGORY);

        model.addAttribute("ozingUsers", ozingUsers);
        model.addAttribute("ozingRoles", ozingRoles);
        model.addAttribute("ozingResources", ozingResources);
        try {
            model.addAttribute("ozingUsersJson", mapper.writeValueAsString(ozingUsers));
            model.addAttribute("ozingRolesJson", mapper.writeValueAsString(ozingRoles));
            model.addAttribute("ozingResourcesJson", mapper.writeValueAsString(ozingResources));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "admin/auth";
    }

    @RequestMapping(value = "/auth", method = RequestMethod.POST)
    public @ResponseBody Object saveAuth(String username, String password, String confirmPassword, String roleName, Long[] ozingUserIds, Long[] ozingRoleIds, Long[] ozingResourceIds, String[] resourceValue, String[] resourceDesc, String _method, HttpServletRequest request, HttpServletResponse response, Model model) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            if (StringUtils.isEmpty(_method) || _method.equalsIgnoreCase("post")) {
                authManager.saveAuth(username, password, confirmPassword, roleName, ozingUserIds, ozingRoleIds, ozingResourceIds, resourceValue, resourceDesc, OZING_CATEGORY, OZING_ADMIN_DEFAULT_ROLES);
            }

            result.put("result", true);
        } catch (IllegalArgumentException e) {
            String message = e.getMessage();
            result.put("result", false);
            result.put("message", message);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("result", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/auth", method = RequestMethod.PUT)
    public @ResponseBody Object updateAuth(String[] roleName, String[] resourceValue,String[] roleDesc, String[] resourceDesc, Long[] ozingRoleIds, Long[] ozingResourceIds, HttpServletRequest request, HttpServletResponse response, Model model) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            authManager.updateAuth(roleName, resourceValue, roleDesc, resourceDesc, ozingRoleIds, ozingResourceIds, OZING_CATEGORY);

            result.put("result", true);
        } catch (IllegalArgumentException e) {
            String message = e.getMessage();
            result.put("result", false);
            result.put("message", message);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("result", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/auth", method = RequestMethod.DELETE)
    public @ResponseBody Object deleteAuth(Long[] userIds, Long[] roleIds, Long[] resourceIds, HttpServletRequest request, HttpServletResponse response, Model model) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            authManager.deleteAuth(userIds ,roleIds, resourceIds, OZING_CATEGORY);

            result.put("result", true);
        } catch (IllegalArgumentException e) {
            String message = e.getMessage();
            result.put("result", false);
            result.put("message", message);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("result", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/auth/password", method = RequestMethod.GET)
    public String toPasswordPage(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "admin/password";
    }

    @RequestMapping(value = "/auth/password", method = RequestMethod.POST)
    public @ResponseBody Object updatePassword(String username, String password, String newPassword, String confirmPassword, HttpServletRequest request, HttpServletResponse response, Model model) {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
            User user = getLoginUser();
            if (user != null || StringUtils.isNotEmpty(username)) {
                if (StringUtils.isEmpty(username)) {
                    username = user.getUsername();
                }
                authManager.updatePassword(username, password ,newPassword, confirmPassword);

                result.put("result", true);
            } else {
                result.put("result", false);
                result.put("message", "请登录");
            }
        } catch (IllegalArgumentException e) {
            String message = e.getMessage();
            result.put("result", false);
            result.put("message", message);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("result", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    private User getLoginUser() {
        if (SecurityContextHolder.getContext() == null || SecurityContextHolder.getContext().getAuthentication() == null) {
            return null;
        }
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof String && principal.equals("anonymousUser")) {
            return null;
        }
        return (User) principal;
    }
}
